<template>
  <!-- 项目实测实量检查排名 -->
  <a-spin :spinning="loading">
    <a-card>
      <title-name :title="`${$route.query.month}月项目实测实量检查排名`"></title-name>
      <div style="padding: 0 20px 20px;">
        <!-- 内部实测实量 -->
        <div v-if="type !== '2.0'" class="mb20">
          <title-name title="内部实测实量"></title-name>
          <div v-if="Object.keys(measurementsMap).length > 0">
            <div v-for="(i, idx) in measurementsMap" :key="idx">
              <div class="branchName">{{ idx }}</div>
              <a-table bordered :rowKey="(record, index) => index" :pagination="false" :columns="columns" :dataSource="i"> </a-table>
            </div>
          </div>
          <Empty v-else description="暂无数据" />
        </div>
         <!-- 第三方实测实量 -->
         <div v-if="type !== '2.1'">
            <div v-if="Object.keys(detailsMap).length > 0">
                <div v-for="(item, index) in detailsMap" :key="index" class="mb20">
                  <title-name :title="index"></title-name>
                  <!-- 当是填报或调整状态，树节点不为《项目实测实量检查排名》，列表类型且为第三方实测实量 -->
                  <!-- <a-button type="primary" icon="plus" v-if="($route.query.editModel == 2 || $route.query.editModel == 4) && queryParam.type !== '2' && index === '第三方实测实量'" @click="visible = true"
                    >添加第三方实测实量</a-button
                  > -->
                  <div v-if="Object.keys(item).length > 0">
                    <div v-for="(i, idx) in item" :key="idx">
                      <div class="branchName">{{ idx }}</div>
                      <a-table bordered rowKey="id" :pagination="false" :columns="columns3" :dataSource="i"> </a-table>
                    </div>
                  </div>
                  <Empty v-else description="暂无数据" />
              </div>
            </div>
            <div v-else>
              <title-name title="第三方实测实量"></title-name>
              <Empty  description="暂无数据" />
            </div>
         </div>
      </div>
    </a-card>
    <!-- 添加或编辑第三方实测实量 -->
    <DialogForm
      :isEmit="false"
      ref="dialogForm"
      :visible.sync="visible"
      edit-model="E"
      :headerTitle="`${form.id ? '编辑' : '添加'}第三方实测实量`"
      :width="1000"
      :form="form"
      :formList="formList"
      :rules="rules"
      @confirm="submitForm"
    />
  </a-spin>
</template>

<script>
import { getActualMeasurement, addThird, updateThird, deleteThird } from '@/api/quality/qualityMonth' // api
import { Empty } from 'ant-design-vue' // 无数据提示
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称

const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    align: 'center',
    customRender() {
      return arguments[1].id !== '0' ? arguments[2] + 1 : ''
    }
  },
  {
    title: '项目名称',
    dataIndex: 'unitName'
  },
  {
    title: '砼结构',
    dataIndex: 'concreteValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '砌体工程',
    dataIndex: 'buildValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '抹灰工程',
    dataIndex: 'plasterValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '机电安装',
    dataIndex: 'electromechanicalValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '装饰装修',
    dataIndex: 'ornamentValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '道路工程',
    dataIndex: 'roadValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '其他',
    dataIndex: 'otherValue',
    align: 'center',
    customRender(e) {
      return e ?? '-'
    }
  },
  {
    title: '平均值',
    dataIndex: 'average',
    customRender(e) {
      return e ?? '-'
    }
  }
]
const columns2 = [
  {
    title: '排名',
    width: 80,
    align: 'center',
    dataIndex: 'index',
    customRender() {
      return arguments[1].id !== '0' ? arguments[2] + 1 : ''
    }
  },
  {
    title: '项目名称',
    width: 230,
    dataIndex: 'projectName'
  },
  {
    title: '平均合格率（%）',
    width: 160,
    dataIndex: 'value'
  },
  {
    title: '劳务分包单位',
    dataIndex: 'subcontractorName'
  }
]

export default {
  name: 'MeasurementInspectionRanking',
  components: {
    Empty,
    DialogForm
  },
  props: {
    // 请求参数
    queryParam: {
      type: Object,
      default: () => null
    }
  },
  data() {
    this.columns = columns
    this.columns2 = columns2
    return {
      type: '',
      loading: false, // 加载控件
      form: {}, // 编辑表单
      visible: false, // 弹窗显隐控件
      rules: {
        branchComId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        subcontractorName: [{ required: true, whitespace: true, message: '请输入班组样板观摩次数', trigger: 'change' }],
        value: [{ required: true, message: '请输入得分', trigger: 'change' }],
        sort: [{ required: true, message: '请输入排名', trigger: 'change' }]
      }, // 校验规则
      detailsMap: {}, // 第三方实测实量
      measurementsMap: {} // 内部实测实量
    }
  },
  computed: {
    // 弹窗表单配置项
    formList() {
      return [
        {
          type: SelectSubCompany,
          keyName: 'branchComId',
          label: '所属分公司',
          viewName: 'branchComName',
          attrs: {
            autoSelected: !this.form.id
          },
          span: 12,
          selectChange: (e) => {
            this.$refs.dialogForm.forms.branchComName = e.orgName
          }
        },
        {
          type: SelectProject,
          keyName: 'projectId',
          label: '所属项目',
          viewName: 'projectName',
          attrs: {
            keyValue: 'branchComId',
            autoSelected: !this.form.id,
            isClear: !this.form.id,
            form: this.form
          },
          span: 12,
          selectChange: (e) => {
            this.$refs.dialogForm.forms.projectName = e.name
          }
        },
        { type: 'BaseInput', keyName: 'subcontractorName', label: '检查名称（月度、季度、区域、全国）', span: 12 },
        { type: 'BaseInputNumber', keyName: 'value', label: '得分', precision: 2, attrs: { min: 0 }, span: 12 },
        { type: 'BaseInputNumber', keyName: 'sort', label: '排名', precision: 0, attrs: { min: 1 }, span: 12 }
      ]
    },
    // 表头
    columns3() {
      let columns = [
        {
          title: '序号',
          width: 80,
          align: 'center',
          dataIndex: 'index',
          customRender() {
            return arguments[1].id !== '0' ? arguments[2] + 1 : ''
          }
        },
        {
          title: '项目名称',
          dataIndex: 'projectName'
        },
        {
          title: '检查名称（月度、季度、区域、全国）',
          dataIndex: 'subcontractorName'
        },
        {
          title: '得分',
          dataIndex: 'value',
          customRender(e) {
            return e ? Number(e).toFixed(2) : '0.00'
          }
        },
        {
          title: '排名',
          dataIndex: 'sort'
        }
      ]
      // 节点若为分公司则添加操作按钮
      // this.queryParam.branchComId &&
      //   (this.$route.query.editModel == 2 || this.$route.query.editModel == 4) &&
      //   columns.push({
      //     title: '操作',
      //     dataIndex: 'actions',
      //     width: '120px',
      //     customRender: (text, record) => {
      //       return (
      //         record.id != '0' && (
      //           <div>
      //             <a
      //               onClick={() => {
      //                 this.visible = true
      //                 this.form = record
      //               }}
      //             >
      //               编辑
      //             </a>
      //             <a
      //               class="del_btn ml12"
      //               onClick={() => {
      //                 this.handleRemove(record.branchComName, record.id)
      //               }}
      //             >
      //               删除
      //             </a>
      //           </div>
      //         )
      //       )
      //     }
      //   })
      return columns
    }
  },
  mounted() {
    // 初始化
    this.init()
  },
  methods: {
    /**
     * 初始化
     */
    init() {
      this.loading = true
      this.type = this.queryParam.type
      console.log(this.type)
      getActualMeasurement(this.queryParam)
        .then((res) => {
          if (res.data) {
            // 计算统计表格的行平均分
            if (res.data.measurementsMap) {
              let measurementsMap = res.data.measurementsMap
              for (const key in measurementsMap) {
                measurementsMap[key].forEach((item) => {
                  let values = ['concreteValue', 'buildValue', 'plasterValue', 'electromechanicalValue', 'roadValue', 'ornamentValue', 'third'] // 参与计算的字段
                  let total = values.reduce((pre, cur) => Number(item[pre] || pre || 0) + Number(item[cur] || 0)) // 总分
                  let num = values.filter((i) => !!item[i])?.length // 有分数的实测实量类型数量
                  item.average = num ? (total / num).toFixed(2) : 0
                })
              }
              res.data.measurementsMap = measurementsMap
            }
            // 映射统计表格信息
            this.detailsMap = res.data.detailsMap || {}
            // 映射列表表格信息
            this.measurementsMap = res.data.measurementsMap || {}
            // 若当前节点为第三方实测实量，且数据列表为空，则默认添加一条空数据以便显示添加按钮
            if (this.queryParam.type === '2.6' && !Object.keys(this.detailsMap)?.length) {
              this.detailsMap['第三方实测实量'] = {}
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * 删除
     * name：分公司
     * id:业务id
     */
    handleRemove(name, id) {
      this.$confirm({
        title: '提示',
        content: '确认删除，删除后不可撤销',
        onOk: () => {
          let form = {
            id,
            qualityMonthId: this.$route.query.id,
            isAdjust: this.$route.query.isAdjust
          }
          return deleteThird(form).then((res) => {
            if (res.code === '0') {
              // 若成功删除表格最后一条数据，则刷新树列表
              this.detailsMap['第三方实测实量'][name]?.length === 2 && this.$emit('refreshTree')
              // 初始化详情
              this.init()
              this.$message.success('删除成功！')
            }
          })
        }
      })
    },
    /**
     * 提交表单
     * form：表单
     */
    submitForm(form) {
      this.$refs.dialogForm.loading = true
      const api = form.id ? updateThird : addThird
      form.qualityMonthId = this.$route.query.id
      form.isAdjust = this.$route.query.isAdjust
      if (!form.id) {
        form.yearMonth = this.queryParam.monthTime
      }
      api(form)
        .then((res) => {
          if (res.code === '0') {
            // 若是id不存在则为新增，并且当前分公司的列表为空，则刷新树列表
            !form.id && !this.detailsMap['第三方实测实量'][form.branchComName] && this.$emit('refreshTree')
            // 初始化详情
            this.init()
            this.$message.success(`${form.id ? '编辑' : '添加'}成功！`)
            this.visible = false
          }
        })
        .finally(() => {
          this.$refs.dialogForm.loading = false
        })
    }
  }
}
</script>

<style scoped>
.branchName {
  padding: 6px 0;
  text-align: center;
  font-weight: bolder;
}
</style>
